/*
 * @Author: hruomei
 * @Title: 工作流公共接口
 * @Description: 包含工作流的公共接口
 * @CreateTime: 2019/08/01
 * @LastUpDateTime: 2019/10/24
 * @Version: V1.0
 */

 /* 2020/09/17   修改所有工作流 发起字段改 "提交"   起草/暂存 改保存 */

import {
	THIS as _this
} from './api.js'
import {
    stephandler,
    handleWFAction,
    getgatherinfo,
    pendingnums,
    pendinginfo,
} from '@/commons/framework/service.js'

const service = {
    getNextStepInfo: '/mp/wfengine/step/getNextStepInfo.do', //获取下一步责任人信息
    getBackInfo: '/mp/wfengine/SelectorNew/getBackInfo.do' //驳回
}

let customListConfgMap = {};

export function getCustomListConfgMap(list) {
    return new Promise((resolve, reject) => {
        function getConfgMap() {
            for (let i = 0, len = list.length; i < len; i++) {
                workflow.getCustomWorkflowList(list[i].MENU_CODE)
                    .then(workflowList => {
                        workflowList.forEach(thisItem => {
                            customListConfgMap[thisItem.id] = thisItem;
                        });

                        resolve(customListConfgMap);
                    }).catch(e => {
                        reject(e);
                    });
            }
        }

        if (!customListConfgMap) {
            getConfgMap();
        } else if (!list.every(item => customListConfgMap[item.WORKFLOW_ID])) {
            customListConfgMap = {};

            getConfgMap();
        } else {
            return resolve(customListConfgMap)
        }
    });
}

export function getCustomListConfgMapSync() {
    return customListConfgMap;
}

const workflow = {
    usernameFilter(str) {
        if (!str || !_this.$api.isString(str)) return str;
        let string = str,
            users = [],
            result;
        if (string.indexOf('(') != -1) {
            let regex = /\((.+?)\)/g;
            let option = str.match(regex)[0];
            if (option.length > 0) {
                string = option.substring(1, option.length - 1);
            }
        }
        if (string.indexOf(',') != -1) {
            users = string.split(',');
            for (let i = 0; i < users.length; i++) {
                if (users[i].indexOf('[') != -1) {
                    let user_b = users[i];
                    users[i] = _this.$api.getBracketStr(user_b) || users[i].split(']')[1];
                }
            }
            result = users.join(',');
        } else {
            if (string.indexOf('[') != -1) {
                let string_b = string;
                string = _this.$api.getBracketStr(string_b) || string.split(']')[1];
            }
            result = string;
        }
        return result;
    },

    currentAuditorFilter(str) {
        if (!str || !_this.$api.isString(str)) return str;
        let string = str,
            users = [],
            result;
        if (string.indexOf('(') != -1) {
            let regex = /\((.+?)\)/g;
            let option = str.match(regex)[0];
            if (option.length > 0) {
                string = option.substring(1, option.length - 1);
            }
        }
        if (string.indexOf(',') != -1) {
            users = string.split(',');
            for (let i = 0; i < users.length; i++) {
                if (users[i].indexOf('[') != -1) {
                    let user_b = users[i];
                    users[i] = _this.$api.getBracketStr(user_b) || users[i].split(']')[1];
                }
            }
            if (users.length > 2) {
                users.length = 2;
                result = `${users.join(',')}等人`
            } else {
                result = `${users.join(',')}`
            }
        } else {
            if (string.indexOf('[') != -1) {
                let string_b = string;
                string = _this.$api.getBracketStr(string_b) || string.split(']')[1];
            }
            result = string;
        }
        return result;
    },

    proccessNameFilter(name) {
    	if(_this.$api.isNull(name)) {
    		return '';
    	}

    	if(name.indexOf('[') != -1) {
    		return name.split('[')[0];
    	}

    	return name;
    },

    timeFilter(time) {
        if (_this.$api.isNull(time)) {
            return '';
        }

        if (_this.$api.now() === time.substring(0, 10)) {
            return time.substring(11, 16); // 如果是当天，则显示时分
        } else {
            return time.substring(5, 16); // 如果非当天，显示日期
        }

        return value;
    },

    getStatusInfo(status) {
        if (_this.$api.isNull(status)) {
            return '';
        }

        let ps = {
            color: '#333',
            name: '未知'
        };

        switch (status) {
            case 0:
                ps = {
                    color: '#6698d9',
                    // name: '草稿'
                    name: '保存' //wxx 2020/09/16 修改描述
                }
                break;
            case 1:
                ps = {
                    color: '#38c797',
                    name: '处理中'
                }
                break;
            case 2:
                ps = {
                    color: '#949494',
                    name: '作废'
                }
                break;
            case 3:
                ps = {
                    color: '#949494',
                    name: '关闭'
                }
                break;
            case 4:
                ps = {
                    color: '#949494',
                    name: '审批通过'
                }
                break;
            case 5:
                ps = {
                    color: '#eb9928',
                    name: '挂起'
                }
                break;
            case 6:
                ps = {
                    color: '#e3666e',
                    name: '驳回'
                }
                break;
        }
        return ps;
    },

    getPendingTypeInfo(status) {
        if (_this.$api.isNull(status)) {
            return '';
        }

        let ps = {
            color: '#333',
            name: '未知'
        };

        switch (status) {
            case 0:
                ps = {
                    color: '#e36666',
                    name: '提交'
                }
                break;
            case 1:
                ps = {
                    color: '#e68332',
                    name: '审批'
                }
                break;
            case 2:
                ps = {
                    color: '#6b8fd6',
                    name: '会签'
                }
                break;
            case 3:
                ps = {
                    color: '#949494',
                    name: '结束'
                }
                break;
            case 4:
                ps = {
                    color: '#3fadd1',
                    name: '抄送'
                }
                break;
            case 5:
                ps = {
                    color: '#9cb32b',
                    name: '沟通'
                }
                break;
            case 6:
                ps = {
                    color: '#36bf91',
                    name: '完成'
                }
                break;
            case 7:
                ps = {
                    color: '#949494',
                    name: '作废'
                }
                break;
            case 8:
                ps = {
                    color: '#949494',
                    name: '不通过'
                }
                break;
            case 9:
                ps = {
                    color: '#3fadd1',
                    name: '发子流程'
                }
                break;
            case 10:
                ps = {
                    color: '#e36666',
                    name: '重新提交'
                }
                break;
            case 11:
                ps = {
                    color: '#d1a111',
                    // name: '草稿'
                    name: '保存' //wxx 2020/09/16 修改描述
                }
                break;
        }
        return ps;
    },

    showQuickAudit(data) {
        if (data.FORMINFO && data.PENDING_TYPE != "4" && data.PENDING_TYPE != "2") {
            let quicktemp = data.FORMINFO.substr(data.FORMINFO.indexOf("quickaudit"));

            quicktemp = quicktemp.split('&')[0];
            quicktemp = quicktemp.split('=')[1];

            if (quicktemp == true || quicktemp == "true") {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    },

    // 点击待办列表项
    dealPendingFn(rowData) {
        let tmp_path = rowData.FORMINFO,
            formData = null,
            G_wfid = '';

        if (tmp_path.indexOf("?") != tmp_path.lastIndexOf("?")) {
            tmp_path = tmp_path.substring(tmp_path.indexOf("?") + 1);
        }

        formData = _this.$api.parseUrlParams(tmp_path);

        if (formData && formData.wfid && formData.wfid.indexOf("G_") == 0) {
            G_wfid = formData.wfid; // 汇总wfid
        }

        let data = {
            status: 1, // (pending_type == 4) ? 0 : 1;/*-1提交流程 0 查看，1处理代办 */
            wfid: rowData.PROCESS_MODULE_ID,
            p_module_name: rowData.PROCESS_MODULE_NAME,
            formPath: rowData.FORMINFO,
            process_guid: rowData.PROCESS_GUID,
            node_guid: rowData.NODE_GUID,
            step_guid: rowData.STEP_GUID,
            pending_type: rowData.PENDING_TYPE,
            G_wfid: G_wfid,
            operat: rowData.PENDING_TYPE == 4 ? '查看抄送' : '处理待办',
            navigationTitle: rowData.PROCESS_MODULE_NAME,
            menuCode: rowData.menuCode,
            current_step_name: rowData.CURRENT_STEP_NAME
        };

        data.status = (data.pending_type == 4) || data.__status_url_open_0_by_routejs ? 0 : 1;

        if (data.G_wfid && data.G_wfid != '') {
            data.isGatherService = true;
        }

        this.getwfSession(data);
    },

    // 查看已办
    viewTask(rowData) {
        let tmp_path = rowData.FORMINFO,
            formData = null,
            G_wfid = '';

        if (tmp_path.indexOf("?") != tmp_path.lastIndexOf("?")) {
            tmp_path = tmp_path.substring(tmp_path.indexOf("?") + 1);
        }

        formData = _this.$api.parseUrlParams(tmp_path);

        if (formData && formData.wfid && formData.wfid.indexOf("G_") == 0) {
            G_wfid = formData.wfid; // 汇总wfid
        }

        let data = {
            status: "0",
            wfid: rowData.WFID,
            p_module_name: rowData.PROCESS_MODULE_NAME,
            formPath: rowData.FORMINFO,
            process_guid: rowData.PROCESS_GUID,
            node_guid: rowData.NODE_GUID,
            step_guid: rowData.STEP_GUID,
            G_wfid: G_wfid,
            current_step_name: rowData.CURRENT_STEP_NAME,
            navigationTitle: `查看-${rowData.PROCESS_MODULE_NAME}`,
            menuCode: rowData.menuCode,
        };

        if (data.G_wfid && data.G_wfid != "") {
            data.isGatherService = true;
        }

        this.getwfSession(data);
    },

    handleDraft(rowData) {
        this.getwfSession({
            status: "1",
            wfid: rowData.NODE_GUID,
            p_module_name: rowData.PROCESS_MODULE_NAME,
            formPath: rowData.FORMINFO,
            process_guid: rowData.PROCESS_GUID,
            node_guid: rowData.NODE_GUID,
            // navigationTitle: `草稿-${rowData.PROCESS_MODULE_NAME}`,
            navigationTitle: `保存-${rowData.PROCESS_MODULE_NAME}`, //wxx 2020/09/16 修改描述
            menuCode: rowData.menuCode
        });
    },

    getUserList(uList) {
        let userlist = uList,
            nextstep_userlist = [];

        if (_this.$api.isString(userlist)) {
            userlist = JSON.parse(userlist);
        }

        if (userlist && userlist.length > 0) {
            userlist.forEach(user => {
                nextstep_userlist.push({
                    "userid": user.id ? user.id : user.user_id,
                    "username": user.text ? user.text : user.user_name
                });
            });
        }

        return nextstep_userlist;
    },

    quickAuditConfirm(quickText, quickParm, menuCode) {
        let formPath = quickParm.formPath && quickParm.formPath != "" ? quickParm.formPath : '',
            objSession = {
                isQuickAudit: true,
                quickText: quickText,
                wfid: quickParm.wfid,
                node_guid: quickParm.node_guid,
                currstepid: quickParm.step_guid,
                business_no: quickParm.business_no && quickParm.business_no.trim() != "" ? quickParm.business_no : Math
                    .random().toString()
                    .substring(2)
            };

        // 不能配置为老表单方式
        formPath = formPath.indexOf("Workflow/StepHandlers/StepHandler.aspx") == -1 ? formPath : '';

        stephandler({
            isstart: 0,
            wfid: quickParm.wfid,
            nodeid: quickParm.node_guid,
            formname: formPath,
            pending_type: 1
        }, menuCode)
    	.then(result => {
            objSession.wfInfo = result;

            if (result && result.success && result.data) {
                let wfData = result.data.rows;

                // 取表单路径
                objSession.businessdata = null;

                // 处理代办
                if (wfData.businessdata.length > 0) {
                    // 取业务数据
                    objSession.businessdata = wfData.businessdata[0].BUSINESSDATA;
                }

                // 当前步聚ID
                if (wfData.stepid) {
                    objSession.currstepid = wfData.stepid;
                }

                if (wfData.businessdata.length > 0) {
                    // 取业务数据
                    objSession.businessdata = wfData.businessdata[0].BUSINESSDATA;
                }

                this.getNextStepInfo(1, objSession, menuCode);
            } else {
                _this.$api.unSuccessHandleFn('快速审批', result);
            }
        }).catch(e => {
            _this.$api.errorHandleFn(e);
        });
    },

    // 获取下一步责任人信息
    getNextStepInfo(actionType, objSession, menuCode) {
        objSession.actionType = actionType;

        let formData = objSession.businessdata,
            next_Json = {
                "currstepid": objSession.currstepid,
                "wfid": (actionType == 0) ? objSession.wfid : objSession.node_guid,
                "business_data": formData,
                "business_no": objSession.business_no,
                "pt": '5'
            },
            requestUrl = `/${menuCode}${service.getNextStepInfo}`,
            method = 'post',
            param = {
                action: actionType,
                showd: false,
                nextJson: encodeURIComponent(JSON.stringify(next_Json))
            };

        // 驳回
        if (actionType == 6) {
            requestUrl = `/${menuCode}${service.getBackInfo}`;
            method = 'get';
            param = {
                action: actionType,
                wfid: (actionType == 0) ? objSession.wfid : objSession.node_guid,
                stepid: objSession.currstepid,
                currstepid: objSession.currstepid
            };
        }

        _this.$lyRequest[method](requestUrl, param).then(result => {
            if (result && result.success && result.data) {
                objSession.nextInfo = result.data.rows; // 下一步骤信息

                if (!(objSession.nextInfo.steps && objSession.nextInfo.steps.length > 0 &&
                        objSession.nextInfo.steps[0].choosesteps[0])) {
                    _this.$api.showTip('找不到下一步骤及下一步责任人');
                    return false;
                }

                this.handleWFAction(result, objSession, menuCode);
            } else {
                _this.$api.unSuccessHandleFn(result);
            }
        }).catch(e => {
            _this.$api.errorHandleFn(e);
        });
    },

    handleWFAction(result, objSession, menuCode) {
        // 由于取不到表单页面上的isTransactionForm数据，故这里默认为false
        let isTransactionForm = false,
            formJsonData = JSON.parse(objSession.businessdata),
            sub_Json = {
                "userinfo": {
                    "userid": _this.$api.getUserInfo().ly_id,
                    "username": _this.$api.getUserInfo().name
                },
                "wfid": (objSession.actionType == 0 || objSession.actionType == 13) ? objSession.wfid : (objSession.G_wfid &&
                    objSession.G_wfid.length > 0 ? objSession.G_wfid : objSession.node_guid),
                "currstepid": objSession.currstepid,
                "actiontype": objSession.actionType,
                "priotiry": "-1",
                "pid": objSession.process_guid,
                "cc": objSession.nextInfo ? this.getUserList(objSession.nextInfo.cc.userlist) : [],
                "handler_text": objSession.isQuickAudit == true ? objSession.quickText : "",
                "attch": [],
                "process_name": "",
                "business_data": objSession.businessdata,
                "business_no": objSession.business_no,
                "pt": '5'
            };

        let succeeFn = () => {
            // 获取动作名称
            let wfData = objSession.wfInfo.data.rows,
                acName = wfData.actionlist.filter(e => {
                    return e.ACTION_TYPE == objSession.actionType;
                })[0].NAME,
                msg = acName + '成功';

            _this.$api.showTip(msg);
        }

        let failFn = result => {
            let msg = result.message.replace('${}', '');

            _this.$api.showModalWithCloseButton(msg, () => {
                if (msg == "当前节点已处理完成") {
                    _this.$api.showTip('当前节点已处理完成');
                } else {
                    if (objSession.isQuickAudit) {
                        objSession.isQuickAudit = false;
                    }
                }
            });
        }

        if (formJsonData && formJsonData.length > 0) {
            formJsonData.forEach(item => {
                // [{business_no: 12344}]
                if (item.key == "business_no") {
                    sub_Json.business_no = item.value; // 取business_no
                }
            });
        }

        if (objSession.actionType != 14) {
            sub_Json.nextstep = this.getSubJsonNextStep(result.data.rows);
        }

        if (!isTransactionForm) {
            handleWFAction({
                subJson: encodeURIComponent(JSON.stringify(sub_Json))
            }, menuCode).then(result => {
                if (result && result.success && result.data) {
                    succeeFn();
                } else {
                    failFn(result);
                }
            }).catch(e => {
                _this.$api.errorHandleFn(e);
            });
        } else {
            succeeFn();
        }
    },

    getSubJsonNextStep(rows) {
        let nextStepList = [];

        if (rows && rows.domainType != 1) {
            rows.steps.forEach(step => {
                step.choosesteps.forEach(nextstep => {
                    if (nextstep.user.ismulti != 1) {
                        // 不支持多人默认取第一个
                        let user = [];

                        if (nextstep.user.userlist.length > 0) {
                            user.push(nextstep.user.userlist[0]);
                        }

                        nextStepList.push({
                            "stepid": nextstep.id,
                            "auditor": this.getUserList(user)
                        });
                    } else {
                        nextStepList.push({
                            "stepid": nextstep.id,
                            "auditor": this.getUserList(nextstep.user.userlist)
                        });
                    }
                });
            });
        }

        return nextStepList;
    },

    getwfSession(data) {
        if (!data) {
            return;
        }

        // -1提交流程 0 查看，1处理代办 -2其它单独页面
        let status = data.status.toString().length > 0 ? data.status : -2,
            isstart = status == -1 ? 1 : 0,
            wfid = data.wfid || '', //流程模板ID
            G_wfid = data.G_wfid || '',
            formPath = data.formPath || '', //表单路径
            process_guid = data.process_guid || 0,
            node_guid = data.node_guid || '',
            step_guid = data.step_guid || '',
            pending_type = data.pending_type || '',
            operat = data.operat || '',
            navigationTitle = data.navigationTitle,
            isGatherService = data.isGatherService || false,
            current_step_name = data.current_step_name || ''

        let objSession = {
            menuCode: data.menuCode,
            pid: process_guid,
            wfid: wfid,
            node_guid: node_guid,
            currstepid: step_guid,
            business_no: Math.random().toString().substring(2),
            pending_type: pending_type,
            G_wfid: G_wfid,
            navigationTitle: navigationTitle,
            isGatherService: isGatherService,
            current_step_name: current_step_name
        };

        // -1提交流程 1处理代办
        if (status == -1 || status == 0 || status == 1) {
            if (data.isGatherService) {
                getgatherinfo({
                    G_wfid: G_wfid
                }, data.menuCode).then(result => {
                    this.handleNavigate(result, objSession, status, formPath);
                }).catch(e => {
                    _this.$api.errorHandleFn(e);
                });
            } else {
                stephandler({
                    isstart: isstart,
                    wfid: wfid,
                    nodeid: node_guid,
                    formname: formPath,
                    pending_type: pending_type,
                    pt: '5' // 平台类型
                }, data.menuCode).then(result => {
                    this.handleNavigate(result, objSession, status, formPath);
                }).catch(_this.$api.errorHandleFn);
            }
        } else {
            // 查看抄送
            if (status == -2) {
                let result = {
                    data: {
                        rows: {
                            actionlist: [{
                                "NAME": '提交',
                                "TYPE": 0
                            }, {
                                // "NAME": '起草',
                                "NAME": '保存',
                                "TYPE": 13
                            }]
                        }
                    }
                }

                objSession.wfInfo = encodeURIComponent(JSON.stringify(result));
                objSession.status = status;
                _this.$api.navigateTo(formPath, objSession);
            }
        }
    },

    handleNavigate(result, objSession, status, formPath) {
        if (result && result.success) {
            let rows = result.data.rows;
            objSession.wfInfo = encodeURIComponent(JSON.stringify(result));
            objSession.businessdata = null;

            if (status == -1) {
                // 提交
                if (rows.form && rows.form[0]) {
                    let pages = getCurrentPages(),
                        page = pages[pages.length - 1];

                    if (page && page.route) {
                        // 不能配置为自身，否则出现加载死循环
                        formPath = rows.form[0].FORM_NAME.indexOf(page.route) == -1 ? rows.form[0].FORM_NAME : '';
                    }
                } else {
                    formPath = '';
                }
            } else {
                // 处理代办
                if (rows.businessdata.length > 0) {
                    // 取业务数据
                    objSession.businessdata = rows.businessdata[0].BUSINESSDATA;
                }

                // 业务单号
                if (rows.businessno.length > 0) {
                    objSession.business_no = rows.businessno;
                }
            }

            // 当前步聚ID
            if (rows.stepid) {
                objSession.currstepid = rows.stepid;
            }

            // 根据表单路径加载表单
            if (!formPath || formPath.indexOf('pages/') == -1) {
                _this.$api.showModalWithCloseButton('未找到流程步骤设置的表单');
                return;
            }

            let targetObjSession = Object.assign({}, objSession);
            targetObjSession.status = status;

            _this.$store.commit('workflow/setWfSession', targetObjSession);
            //2021-6-28增加除代办页，其他页面先关闭再打开
            let pages = getCurrentPages();//当前页
            let beforePage = pages[pages.length - 1];
            if(beforePage.route.indexOf("workflowList") != -1||beforePage.route.indexOf("index") != -1){
                _this.$api.navigateTo(formPath);
            }else{
                _this.$api.redirectTo(formPath);
            }
        } else {
            _this.$api.unSuccessHandleFn(result);
        }
    },

    // 处理邮件待办
    handleWf(obj) {
        if (_this.$config.isEmmApp && !obj.menu_code) {
            throw new Error('handleWf(): menu_code is required.');
        }

        if (!obj.pendingid) {
            throw new Error('handleWf(): pendingid is required.');
        }

        if (obj.username !== _this.$api.getUserInfo().ly_loginname) {
            _this.$api.showModalWithCloseButton('待办责任人和当前登录用户不匹配，无法打开目标链接');
            return;
        }

        // 获取待办打开信息
        pendinginfo({
            pendingid: obj.pendingid,
            pt: 5
        }, obj.menu_code).then(result => {
            if (result.success && result.data) {
                result.data.rows.menuCode = obj.menu_code;
                this.dealPendingFn(result.data.rows);
            } else {
                _this.$api.unSuccessHandleFn(result);
            }
        }).catch(e => {
            _this.$api.errorHandleFn(e);
        });
    },

    // 根据应用编码获取自定义工作流列表
    getCustomWorkflowList(menuCode) {
        return new Promise((resolve, reject) => {
            const customConfg = _this.$config[menuCode];
            if (customConfg && customConfg.workflow) {
                if (_this.$api.isArray(customConfg.workflow)) { // 如果是数组,则直接返回数组
                    resolve(customConfg.workflow);
                } else if (_this.$api.isFunction(customConfg.workflow)) {
                    customConfg.workflow(resolve);
                } else {
                    reject(null);
                }
            } else {
                reject(null);
            }
        });
    },

    // 获取自定义工作流某一项的配置,如果有设置id则根据id匹配,否则根据name匹配
    getCustomActionConfg(item) {
        return new Promise((resolve, reject) => {
            if (customListConfgMap && customListConfgMap[item.WORKFLOW_ID]) {
                return resolve(customListConfgMap[item.WORKFLOW_ID]);
            }

            this.getCustomWorkflowList(item.MENU_CODE).then(workflowList => {
                const confg = workflowList.find(thisItem => {
                    if (thisItem.id) {
                        return thisItem.id === item.WORKFLOW_ID;
                    }

                    return thisItem.name === item.MENU_NAME
                });

                resolve(confg);
            }).catch(e => {
                reject(null);
            });
        });
    },

    getCustomRootPendingNumFn(menuCode) {
        let appConfg =  _this.$config[menuCode];

        // 为了性能考虑,建议将获取待办数量的接口合并为一个,这样可以直接调用配置在根路径下的获取待办数量的接口,而不需要每一个入口项调用一次
        // 但要注意,如果一个应用配置了多个入口,需要返回数组形式的待办数量列表,列表顺序与入口顺序一致
        if (appConfg.getPendingNum && _this.$api.isFunction(appConfg.getPendingNum)) {
            return appConfg.getPendingNum;
        }

        return null;
    },

    // 获取MP2.0工作流待办
    getPendingMPNum(menuCode, callback) {
        if (!callback || !_this.$api.isFunction(callback)) {
            throw new Error('getPendingMPNum(): callback is required or callback is not function');
        }

        pendingnums({
            loading: false,
            pt: '5'
        }, menuCode)
        .then(result => {
            if (result.success) {
                callback(Number(result.data.rows.pending));
            } else {
                callback(0);
            }
        }).catch(e => {
            callback(0);
        });
    },

    // 获取自定义工作流或MP工作流的待办数量
    getPendingNum(item) {
        return new Promise((resolve, reject) => {
            if (item.IS_CUSTOM) {
                const rootFn = this.getCustomRootPendingNumFn(item.MENU_CODE);

                // 为了性能考虑,建议将获取待办数量的接口合并为一个,这样可以直接调用配置在根路径下的获取待办数量的接口,而不需要每一个入口项调用一次
                // 但要注意,如果一个应用配置了多个入口,需要返回数组形式的待办数量列表,列表顺序与入口顺序一致
                if (rootFn) {
                    rootFn(pendingNumS => {
                        resolve(pendingNumS);
                    }, pendingNumF => {
                        resolve(pendingNumF);
                    });
                } else {
                    this.getCustomActionConfg(item).then(confg => {
                        if (confg && confg.getPendingNumFn) {
                            confg.getPendingNumFn(num => {
                                resolve(Number(num));
                            }, e => {
                                resolve(0);
                            });
                        } else {
                            resolve(0)
                        }
    				}).catch(e => {
    					resolve(0)
    				});
                }
            } else {
                this.getPendingMPNum(item.MENU_CODE, num => {
                    resolve(num);
                });
            }
        });
    },

    // 生成工作流列表
    async handleAppList(origionAppList) {
        if (origionAppList.length == 0) return [];

        let allAppList = [];
        customListConfgMap = {};

        for (let i = 0, len = origionAppList.length; i < len; i++) {
            let item = origionAppList[i];

            try {
                let workflowList = await this.getCustomWorkflowList(item.MENU_CODE);

                // 将数组添加到allAppList
                workflowList.forEach(thisItem => {
                    customListConfgMap[thisItem.id] = thisItem;

    				allAppList.push({
    					...item,
    					MENU_NAME: thisItem.name,
    					MENU_IMG: thisItem.icon || '/static/framework/app-icon/default.png',
    					ORG_MENU_NAME: item.MENU_NAME,
    					WORKFLOW_ID: thisItem.id,
                        SHOW_LAUNCH: thisItem.hasOwnProperty('showLaunch') ? thisItem.showLaunch : true,
    					IS_CUSTOM: true,
    					RANGE_INDEX: 2,
    					SELF_INDEX: allAppList.length,
                        GUID: _this.$api.guid()
    				});
                });
            } catch(e) {
    			allAppList.push({
    				...item,
    				ORG_MENU_NAME: item.MENU_NAME,
    				IS_CUSTOM: false,
                    SHOW_LAUNCH: true,
    				RANGE_INDEX: 1,
    				SELF_INDEX: allAppList.length,
                    GUID: _this.$api.guid()
    			});
            }
        }

        // 工作流列表排序,默认工作流排在前面,自定义工作流按照分类排在后面
        allAppList.sort(_this.$api.sortBy("RANGE_INDEX", "SELF_INDEX"));
        return allAppList;
    },

    // 汇总所有流程数据,并设置tabbar角标
    getAllPendingNum(allAppList, callback) {
        let filterList = [];

        allAppList.forEach(app => {
            let appConfg = _this.$config[app.MENU_CODE];

            // 如果直接配置在appExtends中,则每一个应用只调一次接口获取待办数量
            if (appConfg && appConfg.getPendingNum) {
                // 如果列表中不存在此配置项
                if (!(filterList.find(fItem => fItem.MENU_CODE === app.MENU_CODE))) {
                    filterList.push(app);
                }
            } else {
                filterList.push(app);
            }
        });

        let promises = filterList.map(item => {
            return this.getPendingNum(item);
        });

        Promise.all(promises).then(contents => {
            // 如果返回的是列表,需要将列表拉平
    		try {
    			contents = contents.myFlat();
    		} catch(e) {
    			//TODO handle the exception
    			console.error('getAllPendingNum():::', e)
    		}

            contents.forEach((item, index) => {
                allAppList[index].PENDING_NUM = item;
            });

            callback && callback(allAppList);

            // 计算总数，设置tabar badge
            let allPendingNum = contents.reduce((preValue, curValue) => {
                return preValue + Number(curValue);
            }, 0);

            if (allPendingNum > 0) {
                uni.setTabBarBadge({
                    index: 1,
                    text: allPendingNum > 99 ? '99+' : (allPendingNum + '')
                });
            } else {
                uni.removeTabBarBadge({
                    index: 1
                });
            }
        });
    },

    isContainMenu(menuCode) {
    	if (!menuCode) throw new Error('menuCode is required.');

    	const workflowList = _this.$store.getters['app/appList'];

        if (!workflowList) return false;

    	return workflowList.find(item => item.MENU_CODE === menuCode);
    }
}

export default workflow;
